package com.ruoyi.project.rate;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.service.ConfigService;
import com.ruoyi.framework.web.service.DictService;
import com.ruoyi.project.rate.service.KhzDeptService;
import com.ruoyi.project.system.dept.domain.Dept;
import com.ruoyi.project.system.dept.service.DeptServiceImpl;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.dict.domain.DictData;
import com.ruoyi.project.system.dict.service.DictDataServiceImpl;
import com.ruoyi.project.system.dict.service.IDictDataService;
import com.ruoyi.project.system.role.domain.Role;
import com.ruoyi.project.system.role.service.IRoleService;
import com.ruoyi.project.system.role.service.RoleServiceImpl;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import com.ruoyi.project.system.user.service.UserServiceImpl;

@Component
public class Utils implements ApplicationContextAware {
	private static ApplicationContext applicationContext;
	
	public static Dept rootDept() {
		IDeptService deptService = applicationContext.getBean(DeptServiceImpl.class);
		Dept dept = new Dept();
		dept.setParentId(0L);
		List<Dept> deptList = deptService.selectDeptList(dept);
		if (deptList != null && deptList.size() > 0) {
			return deptList.get(0);
		}
		
		return null;
	}
	
	/**
	 * 取得分管领导列表
	 */
	public static List<User> fgldList() {
		IRoleService roleService = applicationContext.getBean(RoleServiceImpl.class);
		IUserService userService = applicationContext.getBean(UserServiceImpl.class);
		List<User> fgldList = new ArrayList<User>();
		List<Role> roleList = roleService.selectRoleAll();
		for (Role role : roleList) {
			if (StringUtils.equals("fgld", role.getRoleKey())) {
				User user = new User();
				user.setRoleId(role.getRoleId());
				fgldList.addAll(userService.selectAllocatedList(user));
				break;
			}
		}
		return fgldList;
	}
	
	/**
	 * 取得监狱长列表角色
	 * @return
	 */
	public static List<User> jyzList() {
		IRoleService roleService = applicationContext.getBean(RoleServiceImpl.class);
		IUserService userService = applicationContext.getBean(UserServiceImpl.class);
		List<User> list = new ArrayList<User>();
		List<Role> roleList = roleService.selectRoleAll();
		for (Role role : roleList) {
			if (StringUtils.equals("jyz", role.getRoleKey())) {
				User user = new User();
				user.setRoleId(role.getRoleId());
				list.addAll(userService.selectAllocatedList(user));
				break;
			}
		}
		return list;
	}
	
	/**
	 * 查询2级组织机构列表
	 * @param sysDeptService
	 * @return
	 */
	public static List<Dept> level2DeptList() {
		IDeptService deptService = applicationContext.getBean(DeptServiceImpl.class);
		List<Dept> result = new ArrayList<Dept>();
		Dept root = Utils.rootDept();
		
		if (root != null) {
			Dept dept = new Dept();
			dept.setParentId(root.getDeptId());
			List<Dept> deptList = deptService.selectDeptList(dept);
			if (deptList != null && deptList.size() > 0) {
				for (Dept d : deptList) {
					result.add(d);
				}
			}
		}
		
		return result;
	}
	
	public static List<Dept> level2DeptListExcludeYubu() {
		List<Dept> result = level2DeptList();
		Iterator<Dept> it =result.iterator();
		while (it.hasNext()) {
			Dept d = it.next();
			if ("狱部".equals(d.getDeptName())) {
				it.remove();
				break;
			}
		}
		
		return result;
	}
	
	public static <E> List<E> emptyIfNull(List<E> input) {
		if (input == null) {
			return new ArrayList<E>();
		}
		return input;
	}
	
	public static Map<String, String> mapDictByValue(String dictType) {
		IDictDataService dictDataService = applicationContext.getBean(DictDataServiceImpl.class);
		DictData dd = new DictData();
		dd.setDictType(dictType);
		List<DictData> list = dictDataService.selectDictDataList(dd);
		Map<String, String> map = new HashMap<String, String>();
		if (list != null) {
			for (DictData d : list) {
				map.put(d.getDictValue(), d.getDictLabel());
			}
		}
		return map;
	}
	
	public static Map<String, String> mapDictByLabel(String dictType) {
		IDictDataService dictDataService = applicationContext.getBean(DictDataServiceImpl.class);
		DictData dd = new DictData();
		dd.setDictType(dictType);
		List<DictData> list = dictDataService.selectDictDataList(dd);
		Map<String, String> map = new HashMap<String, String>();
		if (list != null) {
			for (DictData d : list) {
				map.put(d.getDictLabel(), d.getDictValue());
			}
		}
		return map;
	}
	
    public static Map<String, Dept> mapDeptByDeptId() {
    	IDeptService deptService = applicationContext.getBean(DeptServiceImpl.class);
    	List<Dept> list = deptService.selectDeptList(new Dept());
		Map<String, Dept> map = new HashMap<String, Dept>();
		for (Dept d : list) {
			map.put(d.getDeptId().toString(), d);
		}
		return map;
	}
    
    /**
     * 判断部门是否是监区，否则为科室
     * @param dept
     * @return
     */
    public static boolean isJq(Dept dept) {
    	String deptName = dept.getDeptName();
//    	String[] jq = new String[] {"一监区", "二监区", "三监区",
//    			"四监区", "五监区", "六监区", "七监区",
//    			"八监区", "九监区", "十监区"};
//    	for (String name : jq) {
//    		if (deptName.startsWith(name)) {
//    			return true;
//    		}
//    	}
    	
    	return deptName.contains("监区");
    }
    
    /**
     * 非考评部门
     * @param dept
     * @return
     */
    public static boolean notKhDept(Dept dept) {
    	ConfigService configService = applicationContext.getBean(ConfigService.class);
    	String config = StringUtils.defaultIfBlank(
    			configService.getKey("rate_not_kh_dept"), ",");
    	String deptName = dept.getDeptName();
    	String[] names = config.split(",");
    	for (String name : names) {
    		if (deptName.equals(name)) {
    			return true;
    		}
    	}
    	return false;
    }
    
    public static List<DictData> getKhzListByPageFlag(String pageFlag) {
		if (StringUtils.isBlank(pageFlag)) {
			return new ArrayList<DictData>();
		}
		
		KhzDeptService khzDeptService = applicationContext.getBean(KhzDeptService.class);
		DictService dictService = applicationContext.getBean(DictService.class);
		
		if (Constants.PAGE_FLAG_SUBMIT.equals(pageFlag)
				|| Constants.PAGE_FLAG_KHZ.equals(pageFlag)
				|| Constants.PAGE_FLAG_ADD.equals(pageFlag)
				|| Constants.PAGE_FLAG_EDIT.equals(pageFlag)) {
			return khzDeptService.getKhzDictDataDept(ShiroUtils.getSysDept());
		} else {
			return dictService.getType(Constants.KHZ);
		}
	}
    
    public static String currentMonth() {
		Calendar c = Calendar.getInstance();
		return new SimpleDateFormat("yyyy-MM").format(c.getTime());
	}
    
    public static String lastMonth() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, -1);
		return new SimpleDateFormat("yyyy-MM").format(c.getTime());
	}
    
    public static String getExportAbsoluteFile(String filename) {
        String downloadPath = RuoYiConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }
    
    private static Font fontOfSongti(Workbook wb) {
		Font font = wb.createFont();
		font.setFontName("宋体");
		return font;
	}
	public static Font fontOfSongti11(Workbook wb) {
		Font font = Utils.fontOfSongti(wb);
		font.setFontHeightInPoints((short) 11);
		return font;
	}
	public static Font fontOfSongti11Bold(Workbook wb) {
		Font font = Utils.fontOfSongti11(wb);
		font.setBold(true);
		return font;
	}
	public static Font fontOfSongti12(Workbook wb) {
		Font font = Utils.fontOfSongti(wb);
		font.setFontHeightInPoints((short) 12);
		return font;
	}
	public static Font fontOfSongti12Bold(Workbook wb) {
		Font font = Utils.fontOfSongti12(wb);
		font.setBold(true);
		return font;
	}
	public static Font fontOfSongti14(Workbook wb) {
		Font font = Utils.fontOfSongti(wb);
		font.setFontHeightInPoints((short) 14);
		return font;
	}
	public static Font fontOfSongti14Bold(Workbook wb) {
		Font font = Utils.fontOfSongti14(wb);
		font.setBold(true);
		return font;
	}
	public static Font fontOfSongti20(Workbook wb) {
		Font font = Utils.fontOfSongti(wb);
		font.setFontHeightInPoints((short) 20);
		return font;
	}
	public static Font fontOfSongti20Bold(Workbook wb) {
		Font font = Utils.fontOfSongti20(wb);
		font.setBold(true);
		return font;
	}
	
	public static CellStyle baseBorderStyle(Workbook wb) {
		CellStyle style = wb.createCellStyle();
		style.setWrapText(true);
		style.setBorderLeft(BorderStyle.THIN);
		style.setBorderTop(BorderStyle.THIN);
		style.setBorderRight(BorderStyle.THIN);
		style.setBorderBottom(BorderStyle.THIN);
		return style;
	}
	
	private static CellStyle baseStyle(Workbook wb) {
		CellStyle style = wb.createCellStyle();
		style.setAlignment(HorizontalAlignment.CENTER);
		style.setVerticalAlignment(VerticalAlignment.CENTER);
		style.setWrapText(true);
		style.setBorderLeft(BorderStyle.THIN);
		style.setBorderTop(BorderStyle.THIN);
		style.setBorderRight(BorderStyle.THIN);
		style.setBorderBottom(BorderStyle.THIN);
		return style;
	}
	
	public static CellStyle styleOfSongti11Horizontal(Workbook wb) {
		CellStyle style = Utils.baseStyle(wb);
		style.setFont(Utils.fontOfSongti11(wb));
		return style;
	}
	public static CellStyle styleOfSongti11Vertical(Workbook wb) {
		CellStyle style = Utils.styleOfSongti11Horizontal(wb);
		style.setRotation((short)255);
		return style;
	}
	public static CellStyle styleOfSongti11VerticalBold(Workbook wb) {
		CellStyle style = Utils.styleOfSongti11Horizontal(wb);
		style.setRotation((short)255);
		style.setFont(Utils.fontOfSongti11Bold(wb));
		return style;
	}
	public static CellStyle styleOfSongti14Horizontal(Workbook wb) {
		Font font = Utils.fontOfSongti14(wb);
		CellStyle style = Utils.baseStyle(wb);
		style.setFont(font);
		return style;
	}
	public static CellStyle styleOfSongti20Horizontal(Workbook wb) {
		Font font = Utils.fontOfSongti20(wb);
		CellStyle style = Utils.baseStyle(wb);
		style.setBorderTop(BorderStyle.NONE);
		style.setBorderBottom(BorderStyle.NONE);
		style.setBorderLeft(BorderStyle.NONE);
		style.setBorderRight(BorderStyle.NONE);
		style.setFont(font);
		return style;
	}
	public static CellStyle styleOfSongti20HorizontalBold(Workbook wb) {
		Font font = Utils.fontOfSongti20Bold(wb);
		CellStyle style = Utils.baseStyle(wb);
		style.setFont(font);
		return style;
	}
	
	public static CellStyle styleOfPmDefault(Workbook wb) {
		CellStyle style = Utils.baseStyle(wb);
		style.setFont(Utils.fontOfSongti11(wb));
		return style;
	}
	
	public static CellStyle styleOfPmBlue(Workbook wb) {
		CellStyle style = Utils.baseStyle(wb);
		style.setFont(Utils.fontOfSongti11(wb));
		style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
		style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		return style;
	}
	
	public static CellStyle styleOfPmGreen(Workbook wb) {
		CellStyle style = Utils.baseStyle(wb);
		style.setFont(Utils.fontOfSongti11(wb));
		style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
		style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		return style;
	}
	
	public static CellStyle styleOfPmYellow(Workbook wb) {
		CellStyle style = Utils.baseStyle(wb);
		style.setFont(Utils.fontOfSongti11(wb));
		style.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
		style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		return style;
	}
	
	public static CellStyle styleOfPmLemon(Workbook wb) {
		CellStyle style = Utils.baseStyle(wb);
		style.setFont(Utils.fontOfSongti11(wb));
		style.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
		style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		return style;
	}
    
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if(Utils.applicationContext == null) {
			Utils.applicationContext = applicationContext;
		}
	}
}